<?php
/**
 * 产品促销管理模型
 * @author cjli
 *
 */ 
class PromotionModel extends Model
{
	/**
	 * 批发列表
	 * @return array
	 */
	public static function get_wholesale_list()
	{
		$wholesaleList = array();
		if(S('wholesale_list')){
			$wholesaleList = S('wholesale_list');
		}else{
			$wholesale_db = D('product_wholesale');
			$result = $wholesale_db->where('display=1')->select();
			if($result){
				foreach ($result as $whole){
					$wholesaleList[$whole['product_id']] = $whole;
				}
			}
			S('wholesale_list', $wholesaleList);
		}
		return $wholesaleList;
	}
	
	/**
	 * 尺码列表
	 * @return array
	 */
	public static function get_product_size_list($pid)
	{
		$sizeList = array();
		if(S('size_list_'.$pid)){
			$sizeList = S('size_list_'.$pid);
		}else{
			$size_db = D('product_size');
			$result = $size_db->where('display=1 and product_id='.$pid)->select();
			if($result){
				foreach ($result as $whole){
					$sizeList[$whole['product_id']] = $whole;
				}
			}
			S('size_list_'.$pid, $sizeList);
		}
		return $sizeList;
	}
	
	/**
	 * 获取产品批发信息
	 * @param int $pid 产品ID
	 * @return array
	 */
	public static function get_product_wholesale_info($pid)
	{
//		$wholesale_db = D('product_wholesale');
//		$info = $wholesale_db->where('product_id='.$pid.' AND display=1')->find();
		$wholesaleList = self::get_wholesale_list();
		return isset($wholesaleList[$pid]) ? $wholesaleList[$pid] : false;
	}
	
	/**
	 * 获取批发价格
	 * @param int $pid 产品ID
	 * @param int $qty 数量
	 * @param int $rank_id 会员等级
	 * @return float
	 */
	public static function get_product_wholesale_price($pid, $qty = 1, $rank_id = 0)
	{
		$price = null;
		$wholesaleInfo = self::get_product_wholesale_info($pid);
		if($wholesaleInfo){
			$wholesale_prices = unserialize($wholesaleInfo['prices']);
			//如果设置了等级
			if($wholesaleInfo['rank_ids']){
				$rank_ids = explode(',', $wholesaleInfo['rank_ids']);
				if(in_array($rank_id, $rank_ids)){
						foreach ($wholesale_prices as $val){
							if($qty >= $val['qty']){
								$price = $val['price'];
							}
						}
				}
				//没有设置等级
			}else{
				foreach ($wholesale_prices as $val){
					if($qty >= $val['qty']){
						$price = $val['price'];
					}
				}
			}
		}
		return $price;
	}
	
	/**
	 * 获取产品尺码信息
	 * @param int $pid 产品ID
	 * @return array
	 */
	public static function get_product_size_info($pid)
	{
//		$wholesale_db = D('product_wholesale');
//		$info = $wholesale_db->where('product_id='.$pid.' AND display=1')->find();
		$productSizeList = self::get_product_size_list($pid);
		return isset($productSizeList[$pid]) ? $productSizeList[$pid] : false;
	}
	
	/**
	 * 统计用户红包数量
	 * @param int $pid 产品ID
	 * @return array
	 */
	public static function get_bonus_count($uid)
	{
		if($uid){
			$bonus_db = D('user_bonus');
			$result = $bonus_db->where('used_time=0 and user_id='.$uid)->field('count(*) as number')->find();
		}
		return $result['number'];
	}
}